#include "tableviewheader.h"
#include "devicemanager.h"
#include <QPainter>
#include <QMouseEvent>

TableViewHeader::TableViewHeader(Qt::Orientation orientation, QWidget *parent)
    : QHeaderView(orientation, parent),m_column(0) {
    setSectionsClickable(true);
}

void TableViewHeader::setGroupColumn(int column) {
    m_column = column;
}
/*
    表头方向水平，且开始下标为0时开始绘制
*/
void TableViewHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const {
    QHeaderView::paintSection(painter, rect, logicalIndex);

    // 分割区域：左70%用于分组，右30%用于排序
    int splitPos = rect.width() * 0.7;

    // 绘制分组区域
    QRect groupRect = QRect(rect.left(), rect.top(), splitPos, rect.height());
    painter->drawText(groupRect, Qt::AlignCenter, model()->headerData(logicalIndex, orientation(), Qt::DisplayRole).toString());

    // 绘制排序按钮
    QRect sortRect = QRect(rect.left() + splitPos, rect.top(), rect.width() - splitPos, rect.height());
    painter->drawRect(sortRect);
    painter->drawText(sortRect, Qt::AlignCenter, "S");
}

void TableViewHeader::mousePressEvent(QMouseEvent *event) {
    int logicalIndex = logicalIndexAt(event->pos());
    int headerPos = sectionViewportPosition(logicalIndex);

    QRect headerRect = QRect(headerPos, 0, sectionSize(logicalIndex), height());

    // 分割区域：左70%用于分组，右30%用于排序
    int splitPos = headerRect.width() * 0.7;
    QRect groupRect = QRect(headerRect.left(), headerRect.top(), splitPos, headerRect.height());
    QRect sortRect = QRect(headerRect.left() + splitPos, headerRect.top(), headerRect.width() - splitPos, headerRect.height());

    if (groupRect.contains(event->pos())) {
        emit groupButtonClicked(logicalIndex);
    } else if (sortRect.contains(event->pos())) {
        emit sortButtonClicked(logicalIndex);
    } else {
        QHeaderView::mousePressEvent(event);
    }
}


